import os
import re
import threading
import datetime
from collections import defaultdict
from time import sleep

import numpy as np
import time
from commen.log import Logger
import openpyxl
# import commen.config

def output_result(result_dict):
    total = 0
    dict_num = defaultdict(int)
    max_delay = max(result_dict.keys())
    for t, num in result_dict.items():
        if int(t) < 11:
            dict_num["11ms以内"] += num
        elif int(t) <= 17:
            dict_num['11ms到17ms之间'] += num
        else:
            dict_num[f'11ms到{max_delay}ms之间'] += num
    for info in dict_num.keys():
        print(f"{info}:{dict_num[info]}")
        total += dict_num[info]
    print(f"总数：{total}个")
    print(f"最大{max_delay}ms")
    if (sub1 := dict_num["11ms以内"] / total) > 0.9544:
        print(f"11ms以内{round(sub1 * 100, 2)}%>2σ已满足")
    else:
        print(f"11ms以内{round(sub1 * 100, 2)}%<2σ未满足")

    if (sub2 := (dict_num["11ms以内"] + dict_num['11ms到17ms之间']) / total) > 0.9974:
        print(f"17ms以内{round(sub2 * 100, 2)}%>3σ已满足")
    else:
        print(f"17ms以内{round(sub2 * 100, 2)}%<3σ未满足")

    print(sub1, sub2)
def ImuDatacontinuity():
    #---------读取config文件获取筛选字段内容--------------------------
    # key = commen.config.global_config.getRaw('keywords', 'Imubegincontinuation')
    key = "to_timestamp(147) imu"
    # ---------读取config文件获取筛选字段内容--------------------------
    #-----------------------创建excel--------------------------------------------
    # 获取当前时间
    time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
    # 获取当前路径
    result_root = os.getcwd()
    root = os.getcwd()
    result_path = result_root + r'\result' + "\\" + time_now
    log_path = root + r'\original-logfile' + '\\'
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    for root, dirs, files in os.walk(log_path):
        for file in files:
            if "Data" in file:
                aa = os.path.join(root, file)
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    book = openpyxl.Workbook()  # 打开一个将写的文件
    sheet = book.create_sheet(index=0)  # 在将写的文件创建sheet
    saveExcel = result_path+"imu延时验证结果.xlsx"
    sheet.cell(1, 2).value = "muc发出imu数据时间"
    sheet.cell(1, 3).value = "算法收到imu数据时间"
    sheet.cell(1, 4).value = "mcu发送imu数据到算法的时间延时"


    row =1
    #-----------------------创建excel--------------------------------------------

    logger  = Logger(logger='TestMylog').getlog()
    fm = open(aa, 'r', encoding='UTF-8') # 打开目标文件
    logger.info("打开目标文件")
    lines = fm.readlines()
    logger.info("获取内容")
    num= 0
    log_DataProctime_list=[]
    imutime_list = []
    list= []
    logger.info("开始逐行读取")
    disc = defaultdict(int)
    for lines in lines: # 对内容 进行逐行读取

        if key in lines: # kye是读取config文件获取的筛选字段
            num = num+1
            bbxitongtime= lines[:lines.index("<thread")] #根据关键字“log_mcucomm”截取前面的系统时间戳
            e = lines[lines.rfind(key):lines.rfind('(0)')]
            e = e[e.rfind(key):e.rfind('(42)')]
            e = e[e.rfind(key):e.rfind('(10)')]
            e = e[e.rfind(key):e.rfind('(52)')]
            e = e[e.rfind(key):e.rfind('(53)')]
            aatime = e.split(key)
            imutime_list.append(aatime[1])
            aa= lines.split("=>")  #截取数据=>末尾的字符串时间戳
            list.append(aa[1])#追加到list中
            log_DataProctime_list.append(bbxitongtime)
    logger.info("开始判断差值")
    for i in range(len(log_DataProctime_list)):
        row =row+1
        sheet.cell(row, 2).value = imutime_list[i]
        sheet.cell(row, 3).value = log_DataProctime_list[i]
        t1 = imutime_list[i].rstrip()
        t1 = t1.lstrip()
        t2 =log_DataProctime_list[i].lstrip()
        t2 = t2.rstrip()
        t1 = datetime.datetime.strptime(t1, '%Y-%m-%d %H:%M:%S.%f')
        t2 = datetime.datetime.strptime(t2, '%Y-%m-%d %H:%M:%S.%f')
        try:

            t1 = int(time.mktime(t1.timetuple()) * 1000.0 + t1.microsecond / 1000.0)
            t2 = int(time.mktime(t2.timetuple()) * 1000.0 + t2.microsecond / 1000.0)
            deltat = int(t2) - int(t1)
            sheet.cell(row, 4).value = deltat
            disc[deltat] += 1
        except:
            sheet.cell(row, 4).value = str(int((t2 - t1).microseconds / 1000))
        logger.info("开始判断:"+log_DataProctime_list[i]+"与"+imutime_list[i]+"差值")




    sleep(2)
    print(disc)
    output_result(disc)
    #----------------------将对比的数据写入excel---------------------------------
    book.save(saveExcel)
    # input("输入任意键继续")
    #----------------------将对比的数据写入excel---------------------------------

ImuDatacontinuity()
